// detailService.ts
import { ref } from 'vue';
import { message } from 'ant-design-vue';

// 导入其他服务
import {
    fetching,
    departmentList,
    selectedDepartment,
    selectedDept,
    onDepartmentSearch,
    onDepartmentChange,
    onDepartmentBlur,
    resetDepartmentData,
} from './departmentService.ts';
import {
    fetching as roleFetching,
    roleList,
    selectedRole,
    selectedRoleObj,
    newRoleName,
    isRoleNew,
    onRoleSearch,
    onRoleFocus,
    onRoleBlur,
    onRoleChange,
    createNewRole,
    resetRoleData,
} from './roleService.ts';
import {
    fetching as businessFetching,
    businessList,
    selectedBusiness,
    selectedBusinessObj,
    newBusinessName,
    isBusinessNew,
    onBusinessSearch,
    onBusinessFocus,
    onBusinessBlur,
    onBusinessChange,
    createNewBusiness,
    resetBusinessData,
} from './businessService.ts';
import {
    fetching as fmFetching,
    failModes,
    fmSearchList,
    fmFocusIndex,
    fmFocus,
    onFmSearch,
    onFmChange,
    onFmBlur,
    addFailMode,
    createNewFailMode,
    fetchFailModes,
    expandFailMode,
    removeFailMode,
    initializeFailModeFromRecord,
    resetFailModeData, fmList
} from './failModeService.ts';
import {
    fetching as cpFetching,
    cpSearchList,
    cpList,
    onCpSearch,
    onCpChange,
    onCpBlur,
    createNewCtrlPlan,
    addCtrlPlan,
    removeCtrlPlan, fetchCtrlPlans,
} from './ctrlPlanService.ts';
import {
    fetching as capacityFetching,
    capacityList,
    onCapacitySearch,
    onCapacityChange,
    onCapacityBlur,
    createNewCapacity,
    resetCapacityData,
} from './capacityService.ts';
import {
    frequencySearchList,
    fetchFrequencies,
    onFrequencySearch,
    onFrequencyChange,
    onFrequencyBlur,
    createNewFrequency,
    resetFrequencyData, frequencyList
} from './frequencyService.ts';
import {
    reactionPlanSearchList,
    onReactionPlanSearch,
    onReactionPlanChange,
    onReactionPlanBlur,
    createNewReactionPlan,
    fetchReactionPlans,
    resetReactionPlanData, reactionPlanList
} from './reactionPlanService.ts';
import type {DtoCtrlPlan, DtoFailMode4requirementList, DtoRequirementDetails, Requirement} from "./type.ts";
import api from "@/utils/api";

// 响应式变量
export const requirementValue = ref<string>('');
export const saving = ref(false);
export const requirementDetails = ref<DtoRequirementDetails>();
//TODO 改版计划，用requirementDetails做信息容器，各个输入框下拉框有结果后往里面填

// 角色相关方法
export const handleRoleFocus = () => {
    onRoleFocus(selectedDepartment.value);
};

export const handleRoleSearch = (value: string) => {
    if (selectedDept.value) {
        onRoleSearch(value, selectedDept.value.nameCn);
    }
};

export const handleNewRoleCreation = async () => {
    if (isRoleNew.value) {
        await createNewRole(selectedDept.value.id, newRoleName.value);
    }
};

// 业务相关方法
export const handleBusinessFocus = () => {
    onBusinessFocus(selectedRole.value);
};

export const handleBusinessSearch = (value: string) => {
    if (selectedRoleObj.value) {
        onBusinessSearch(value, selectedRoleObj.value.name);
    } else {
        onBusinessSearch(value, newRoleName.value);
    }
};

export const handleNewBusinessCreation = async () => {
    if (isBusinessNew.value) {
        await createNewBusiness(selectedRoleObj.value.id, newBusinessName.value);
    }
};

export const requirement = ref<Requirement>();
export const handleNewRequirementCreation = async () => {
    requirement.value={
        id:undefined,
        roleCaseId:selectedBusinessObj.value.roleCaseId,
        value:requirementValue.value,
    }
    try {
        fetching.value = true;

        await api.post('/requirement', requirement.value);

        // 重新获取申请单列表以更新数据
        const response = await api.get('/requirement', {
            params: {
                roleCaseId:selectedBusinessObj.value.roleCaseId,
                value:requirementValue.value,
            }
        });
        requirement.value={
            id:response.data[0].id,
            roleCaseId:response.data[0].roleCaseId,
            value:response.data[0].value,
        }

        message.success(`新申请单【${requirementValue.value}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建申请单失败');
        console.error('创建申请单失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

export const handleNewFmCreation = async (requirementId:any) => {
    if(selectedBusinessObj.value.roleCaseId){
        for (const fm of failModes.value) {
            if(fm.id===undefined && requirementId){
                await createNewFailMode(selectedBusinessObj.value.roleCaseId, fm.modeDesc,requirementId);
            }
        }
        await fetchFailModes(selectedBusinessObj.value.roleCaseId);
        failModes.value.forEach(fm => {
            if(fm.id===undefined){
                const nfm=fmList.value.find(f =>
                    f.modeDesc===fm.modeDesc);
                if(nfm){
                    fm.id=nfm.id;
                }
            }
        });
    }
};

export const handleNewCapacityCreation = async () => {
    if(selectedBusinessObj.value.roleCaseId){
        for (const fm of failModes.value) {
            for (const cp of fm.ctrlPlans) {
                if(cp.capacityId===undefined ){
                    await createNewCapacity(cp.capacityCn);
                    const nCapacity=capacityList.value.find(cap => cap.cnDesc===cp.capacityCn)
                    if(nCapacity){
                        cp.capacityId=nCapacity.id;
                    }
                }
            }
        }

    }
};

export const handleNewCpCreation = async (requirementId:any) => {
    if(selectedBusinessObj.value.roleCaseId){
        for (const fm of failModes.value) {
            for (const cp of fm.ctrlPlans) {
                if(cp.id===undefined && requirementId){
                    await createNewCtrlPlan(fm.id, cp.spec,cp.capacityId,requirementId);
                }
            }
            await fetchCtrlPlans(fm.id);
            fm.ctrlPlans.forEach(cp => {
                if(cp.id===undefined){
                    const ncp=cpList.value.find(p =>
                        p.spec===cp.spec);
                    if(ncp){
                        cp.id=ncp.id;
                    }
                }
            });
        }

    }
};

export const handleNewFrequencyCreation = async () => {
    if(selectedBusinessObj.value.roleCaseId){
        for (const fm of failModes.value) {
            for (const cp of fm.ctrlPlans) {
                for (const fq of cp.frequencies) {
                    if(fq.id===undefined){
                        await createNewFrequency(fq.cnDesc);
                        const nfq=frequencyList.value.find(ifq => ifq.cnDesc===fq.cnDesc)
                        if(nfq){
                            fq.id=nfq.id;
                        }
                    }
                }
            }
        }
    }
};

export const handleNewReactionPlanCreation = async () => {
    if(selectedBusinessObj.value.roleCaseId){
        for (const fm of failModes.value) {
            for (const cp of fm.ctrlPlans) {
                for (const rp of cp.reactionPlans) {
                    if(rp.id===undefined){
                        await createNewReactionPlan(rp.cnDesc);
                        const nrp=reactionPlanList.value.find(irp => irp.cnDesc===rp.cnDesc)
                        if(nrp){
                            rp.id=nrp.id;
                        }
                    }
                }
            }
        }
    }
};

async function handleUpdateData(value: Requirement) {
    const details = ref<DtoRequirementDetails>();
    details.value = {
        id: value.id,
        roleCaseId: value.roleCaseId,
        value: value.value,
        dtoFailMode4requirementList: [],
    }
    failModes.value.forEach(fm => {
        const iFm = ref<DtoFailMode4requirementList>();
        iFm.value = {
            fmId: fm.id,
            fmDesc: fm.modeDesc,
            ctrlPlans: [],
        }
        fm.ctrlPlans.forEach(cp => {
            const iCp = ref<DtoCtrlPlan>();
            iCp.value = {
                cpId: cp.id,
                cpSpec: cp.spec,
                capacityId: cp.capacityId,
                capacityCn: cp.capacityCn,
                frequencyList: [],
                reactionPlanList: [],
            }
            cp.frequencies.forEach(fq => {
                iCp.value?.frequencyList.push(fq);
            });
            cp.reactionPlans.forEach(rp => {
                iCp.value?.reactionPlanList.push(rp);
            });
            iFm.value?.ctrlPlans.push(iCp.value);
        });
        details.value?.dtoFailMode4requirementList.push(iFm.value);
    });
    await api.put('/requirement/relations/dtoRequirementDetails', details.value);
}

// 保存功能
export const handleSave = async (props: any, emit: any) => {
    try {
        if (props.mode === 'preview') return;

        saving.value = true;

        // 验证必填字段
        if (!selectedDepartment.value) {
            message.error('请选择业务部门');
            return;
        }

        if (!selectedRole.value) {
            message.error('请选择角色');
            return;
        }

        if (!selectedBusiness.value) {
            message.error('请选择业务');
            return;
        }

        // 处理新角色和业务的创建
        await handleNewRoleCreation();
        await handleNewBusinessCreation();
        await handleNewRequirementCreation();
        if(requirement.value && requirement.value.id){
            await handleNewFmCreation(requirement.value.id);
            await handleNewCapacityCreation();
            await handleNewCpCreation(requirement.value.id);
            await handleNewFrequencyCreation();
            await handleNewReactionPlanCreation();
            await handleUpdateData(requirement.value);
        }

        message.success("需求申请单保存成功");

        // 保存成功后重置表单
        await resetAllData();
        emit('close');

    } catch (err) {
        console.error('保存失败:', err);
        message.error('保存失败，请重试');
    } finally {
        saving.value = false;
    }
};

// 数据初始化
export const initializeFromRecord = async (record: any, mode: string) => {
    if (mode === 'preview') {
        if (record.dpmNameCn) {
            selectedDepartment.value = record.dpmNameCn;
        }
        if (record.roleName) {
            selectedRole.value = record.roleName;
            selectedRoleObj.value={
                name:record.roleName,
            }
        }
        if (record.businessName) {
            selectedBusiness.value = record.businessName;
            selectedBusinessObj.value={
                name:record.businessName,
                roleCaseId:record.roleCaseId,
            }
        }
        requirementValue.value = record.value || '';
        initializeFailModeFromRecord(record);
    } else {
        // 添加模式：获取选项数据
        await fetchInitialData();
    }
};

export const fetchInitialData = async () => {
    try {
        await fetchFrequencies();
        await fetchReactionPlans();
        // 容量数据会在需要时懒加载
    } catch (error) {
        console.error('初始化数据失败:', error);
    }
};

// 重置所有数据
export const resetAllData = async () => {
    resetDepartmentData();
    resetRoleData();
    resetBusinessData();
    resetFailModeData();
    resetCapacityData();
    resetFrequencyData();
    resetReactionPlanData();
    requirementValue.value = '';
};

// 导出所有需要的响应式数据和函数
export {
    // department
    fetching,
    departmentList,
    selectedDepartment,
    selectedDept,
    onDepartmentSearch,
    onDepartmentChange,
    onDepartmentBlur,

    // role
    roleFetching,
    roleList,
    selectedRole,
    selectedRoleObj,
    newRoleName,
    isRoleNew,
    onRoleSearch,
    onRoleFocus,
    onRoleBlur,
    onRoleChange,

    // business
    businessFetching,
    businessList,
    selectedBusiness,
    selectedBusinessObj,
    newBusinessName,
    isBusinessNew,
    onBusinessSearch,
    onBusinessFocus,
    onBusinessBlur,
    onBusinessChange,

    // fail modes
    fmFetching,
    failModes,
    fmSearchList,
    fmFocusIndex,
    fmFocus,
    onFmSearch,
    onFmChange,
    onFmBlur,
    addFailMode,
    expandFailMode,
    removeFailMode,
    initializeFailModeFromRecord,

    // control plans
    cpFetching,
    cpSearchList,
    onCpSearch,
    onCpChange,
    onCpBlur,
    addCtrlPlan,
    removeCtrlPlan,

    // capacity
    capacityFetching,
    capacityList,
    onCapacitySearch,
    onCapacityChange,
    onCapacityBlur,

    // frequency
    frequencySearchList,
    fetchFrequencies,
    onFrequencySearch,
    onFrequencyChange,
    onFrequencyBlur,

    // reaction plan
    reactionPlanSearchList,
    onReactionPlanSearch,
    onReactionPlanChange,
    onReactionPlanBlur,
};